//
//  HomeViewController.m
//  Rail
//
//  Created by hychen on 2018/2/25.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "HomeViewController.h"
#import "BMMergeViews.h"
#import "HomeTableSectionView.h"
#import "HomeNavSearchView.h"
#import "NewsTableViewCell.h"
#import "HomeNotificationCell.h"
#import "HomeCubeView.h"
#import "WorkTableViewCell.h"
#import "CycleScrollView.h"
#import "HomeVideoView.h"
#import <SDCycleScrollView/SDCycleScrollView.h>

#import "UINavigationBar+Background.h"

#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>

#import "ScanViewController.h"
#import "HomeSearchViewController.h"
#import "HomeAllFunctionController.h"
#import "WatchVideoViewController.h"
#import "CarLogViewController.h"
#import "ObserverLineViewController.h"
#import "SelectUserViewController.h"
#import "FactoryDetailViewController.h"
#import "SelectFactoryViewController.h"
#import "IndustryNewsViewController.h"
#import "IndustryNewDetailViewController.h"
#import "FactoryDetailViewController.h"
#import "LineManageViewController.h"
#import "NoticeDetailViewController.h"

#import "CubeJumpTool.h"

@interface HomeViewController () <SDCycleScrollViewDelegate,CycleScrollViewDelegate>

@property (nonatomic, strong) NSArray<HomeCycleModel *> *cycleImageArray;
@property (nonatomic, strong) NSArray<WorkAreaModel *> *workAreaArray;
@property (nonatomic, strong) NSArray<NoticeModel *> *noticeArray;
@property (nonatomic, strong) NSArray<WarnModel *> *warnArray;
@property (nonatomic, strong) NSArray<NewsModel *> *newsDirArray;
@property (nonatomic, strong) NSArray<HomeVideoHistoryModel *> *videoArray;

@property (nonatomic, strong) NSArray *cycleNoticeArray;

@property (nonatomic, strong) SDCycleScrollView *cycleView;

@property (nonatomic, strong) HomeNavSearchView *navView;

@property (nonatomic, strong) BMMergeViews *mergeView;
@property (nonatomic, strong) HomeCubeView *cubeView;

@property (nonatomic, assign) BOOL isFaving;

@property (nonatomic, assign) CGFloat alphaHeight;
@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    [self scrollViewDidScroll:self.tableView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self scrollViewDidScroll:self.tableView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.backgroundColor = Color_NavBgColor;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _alphaHeight = SCREEN_WIDTH<=375?180:210;
    
    BMWeakSelf
    NSInteger width = SCREEN_WIDTH < 375 ? 200 : SCREEN_WIDTH < 414 ? 240 : 270;
    HomeNavSearchView *navView = [[HomeNavSearchView alloc] initWithFrame:CGRectMake(0, 0, width, 32)];
    self.navView = navView;
    self.navigationItem.titleView = navView;
    [navView setBlockClickSearch:^{
        [weakSelf clickNavSearch];
    }];
    
    [self isShowBackBtn:NO];
    
    [self.navigationItem addRightNavItem:self normalImage:[UIImage imageNamed:@"home_rd_n_ic"] highlightedImage:[UIImage imageNamed:@"home_rd_p_ic"] selector:@selector(clickScanButton)];
 
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(SCREEN_HEIGHT-kTabbarHeight);
    }];
    
    UIColor *color = Color_NavBgColor;
    self.navigationController.navigationBar.barTintColor = color;
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    
    [self renderHeaderView];
    
    [self.tableView.mj_header beginRefreshing];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [BMPhotoIOTool sharedTool];
    });
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)clickScanButton {
    ScanViewController *scanVc = [ScanViewController new];
    [self.navigationController pushViewController:scanVc animated:YES];
}

- (void)clickNavSearch {
    HomeSearchViewController *searchVc = [HomeSearchViewController new];
    [self.navigationController pushViewController:searchVc animated:YES];
}

#pragma mark - HeaderView
- (void)renderHeaderView
{
    [self.mergeView removeFromSuperview];
    
    BMWeakSelf
    NSMutableArray *arrayViews = [NSMutableArray array];
    
    //轮播图
    if (self.cycleImageArray.count > 0) {
        NSMutableArray *titleArray = [NSMutableArray array];
        NSMutableArray *imageArray = [NSMutableArray array];
        for (HomeCycleModel *model in self.cycleImageArray) {
            [titleArray addObject:model.title?:@""];
            [imageArray addObject:model.img_url?:@""];
        }
        SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, Screen_Width, SCREEN_WIDTH<=375?180:210) delegate:self placeholderImage:[UIImage imageNamed:@"home_slideshow_img"]];
        cycleScrollView.showPageControl = YES;
        cycleScrollView.imageURLStringsGroup = imageArray;
        cycleScrollView.titlesGroup = titleArray;
        cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
        cycleScrollView.autoScrollTimeInterval = 6;
        self.cycleView = cycleScrollView;
        [arrayViews addObject:cycleScrollView];
    }
    
    //小方块工具栏
    NSArray *cubeArray = [HomeCubeModel mj_objectArrayWithKeyValuesArray:@[@{@"title":@"视频监控",@"image":@"home_video_surveillance_ic",@"sign":@"videoctrl"},
                                                                           @{@"title":@"设备管理",@"image":@"home_equipment_management_ic",@"sign":@"devicectrl"},
                                                                           @{@"title":@"车辆登记",@"image":@"home_vehicle_registration_ic",@"sign":@"carreg"},
                                                                           @{@"title":@"人脸采集",@"image":@"home_face_collect_ic",@"sign":@"faceget"},
                                                                           @{@"title":@"巡线管理",@"image":@"home_patrol_management_ic",@"sign":@"linectrl"},
                                                                           @{@"title":@"更多",@"image":@"home_more_ic",@"sign":@"more"},]];
    HomeCubeView *cubeView = [[HomeCubeView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 190)];
    self.cubeView = cubeView;
    [cubeView setModelArray:cubeArray];
    [cubeView setBlockClickCube:^(NSInteger index, NSString *sign) {
        [CubeJumpTool clickCubeButton:index sign:sign];
    }];
    [arrayViews addObject:cubeView];
    
    //广播
    if (self.noticeArray.count > 0) {
        NSMutableArray *array = [NSMutableArray array];
        NSMutableArray *modelArray = [NSMutableArray array];
        for (NoticeModel *model in self.noticeArray) {
            if (![model isKindOfClass:[NoticeModel class]]) {
                continue;
            }
            HomeNotificationCell *noticeView = [[[NSBundle mainBundle] loadNibNamed:@"HomeNotificationCell" owner:nil options:nil] lastObject];
            [noticeView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
            [noticeView setModel:model];
            [modelArray addObject:model];
            [array addObject:noticeView];
        }
        
        if (array.count < 3 && self.warnArray.count > 0) {
            NSInteger addCount = self.warnArray.count > 3 - array.count ? (3 - array.count) : self.warnArray.count;
            // 公告数量少于3时 用报警记录补充
            for (int i = 0; i < addCount; ++i) {
                WarnModel *model = [self.warnArray objectAtIndexSafe:i];
                if ([model isKindOfClass:[WarnModel class]]) {
                    HomeNotificationCell *noticeView = [[[NSBundle mainBundle] loadNibNamed:@"HomeNotificationCell" owner:nil options:nil] lastObject];
                    [noticeView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
                    [noticeView setWarnModel:model];
                    [modelArray addObject:model];
                    [array addObject:noticeView];
                }
            }
        }
        
        UIView *bgView = [UIView new];
        bgView.backgroundColor = [UIColor whiteColor];
        CycleScrollView *scrollView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80) cycleDirection:EnumCycleDirectionLandscape cycleViews:array bgView:bgView];
        scrollView.delegate = self;
        [scrollView startTimer];
        [arrayViews addObject:scrollView];
        self.cycleNoticeArray = modelArray;
    }
    
    //视频记录
    if ([self.videoArray isKindOfClass:[NSArray class]] && self.videoArray.count > 0) {
        HomeVideoView *videoView = [[HomeVideoView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, [HomeVideoView heightForVideoViewWithDataArray:self.videoArray])];
        videoView.backgroundColor = kWhiteColor;
        [videoView reloadWithDataArray:self.videoArray];
        [videoView setBlockClickItem:^(HomeVideoHistoryModel *model) {
            SelectVideoDeviceModel *deviceModel = [[SelectVideoDeviceModel alloc] initWithHomeVideoModel:model];
            [JumpTool gotoWatchVideoVc:weakSelf deviceModel:deviceModel];
            NSLog(@"跳转视频记录:%@,%@",model.area_name,model.device_name);
        }];
        [arrayViews addObject:videoView];
    }
    
    //首页头部组合
    self.mergeView = [[BMMergeViews alloc] initWithMergeView:[NSArray arrayWithArray:arrayViews] originY:0];
    self.tableView.tableHeaderView = self.mergeView;

}

#pragma mark 方块点击


#pragma mark - 网络请求
- (void)refreshData {
    [self requestHomeData];
}

- (void)requestHomeData {
    BMWeakSelf
    [HttpRequest loadHomeListDataSuccess:^(HomeDataModel* model) {
        weakSelf.cycleImageArray = model.image_list;
        weakSelf.workAreaArray = model.workarea_list;
        weakSelf.noticeArray = model.notice_list;
        weakSelf.warnArray = model.alert_list;
        weakSelf.newsDirArray = model.news_list;
        weakSelf.videoArray = model.video_history_list;
        
        weakSelf.navigationController.navigationBar.translucent = model.image_list.count > 0;
        
        weakSelf.dataArray = [NSMutableArray arrayWithObjects:weakSelf.workAreaArray?:@[], nil];
        for (NewsDirModel *newDirModel in model.news_list) {
            [weakSelf.dataArray addObject:newDirModel];
        }
        [weakSelf renderHeaderView];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_header endRefreshing];
    } failure:^(NSString *code, NSString *msg) {
        Show_SV_Error_Msg(msg)
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

- (void)addFavWorkArea:(WorkAreaModel *)model button:(UIButton *)btn {
    if (self.isFaving) {
        return;
    }
    self.isFaving = YES;
    Show_NoMsg
    BMWeakSelf
    [HttpRequest addFavWithLineId:@"" areaId:model.areaid deviceId:@"" success:^(id object) {
        //收藏成功
        if ([object isKindOfClass:[NSNumber class]]) {
            //收藏id
            NSNumber *favId = (NSNumber *)object;
            model.favid = [favId stringValue];
        }
        else if ([object isKindOfClass:[NSString class]]) {
            //收藏id
            NSString *favId = (NSString *)object;
            model.favid = favId;
        }
        model.is_fav = YES;
        btn.selected = YES;
        weakSelf.isFaving = NO;
        Show_Msg_Success(@"收藏成功")
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        weakSelf.isFaving = NO;
    }];
}

- (void)cancelFavWorkArea:(WorkAreaModel *)model button:(UIButton *)btn {
    if (self.isFaving) {
        return;
    }
    self.isFaving = YES;
    Show_NoMsg
    BMWeakSelf
    [HttpRequest cancelFavWithFavId:model.favid success:^(id object) {
        model.favid = nil;
        model.is_fav = NO;
        btn.selected = NO;
        weakSelf.isFaving = NO;
        Show_Msg_Success(@"取消收藏成功")
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
        weakSelf.isFaving = NO;
    }];
}

#pragma mark - SDCycleScrollView
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
    
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    HomeCycleModel *model = [self.cycleImageArray objectAtIndexSafe:index];
    if (model) {
        [JumpTool gotoWebVcWithUrl:model.jump_url viewController:self];
    }
}

#pragma mark - CycleScrollViewDelegate
- (void)cycleScrollViewDelegate:(CycleScrollView *)cycleScrollView didSelectView:(int)index {
    WarnModel *model = [self.cycleNoticeArray objectAtIndexSafe:index-1];
    if ([model isKindOfClass:[NoticeModel class]]) {
        [self gotoNoticeDetail:(NoticeModel *)model];
    }
    else if ([model isKindOfClass:[WarnModel class]]) {
        WarnDetailModel *warnModel = [WarnDetailModel new];
        warnModel.recordid = model.recordid;
        warnModel.start_time = model.start_time;
        warnModel.areaid = model.areaid;
        warnModel.deviceid = model.deviceid;
        warnModel.alert_type = model.alert_type;
        [JumpTool gotoWarnDetailVcWithModel:warnModel vc:self];
    }
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"offsetY:%f",scrollView.contentOffset.y);
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY <= _alphaHeight && self.cycleImageArray.count > 0) {
        CGFloat alpha = MIN(1, offsetY / _alphaHeight);
        alpha = MAX(0.01, alpha);
        [[[self.navigationController.navigationBar subviews] objectAtIndex:0] setAlpha:alpha];
    } else {
        [[[self.navigationController.navigationBar subviews] objectAtIndex:0] setAlpha:1];
        //---end---
    }
}

#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    id object = [self.dataArray objectAtIndex:section];
    if ([object isKindOfClass:[NSArray class]]) {
        return ((NSArray *)object).count;
    }
    else if ([object isKindOfClass:[NewsDirModel class]]) {
        return ((NewsDirModel *)object).list.count;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section > 0) {
        NewsDirModel *dirModel = [self.dataArray objectAtIndex:section];
        if ([dirModel isKindOfClass:[NewsDirModel class]]) {
            HomeTableSectionView *sec = [HomeTableSectionView sectionView];
            sec.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
            sec.titleLabel.text = dirModel.dir_name;
            BMWeakSelf
            [sec setBlockClickRight:^{
                [weakSelf gotoMoreIndustryNews:dirModel];
            }];
            return sec;
        }
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section > 0) {
        return 50;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id object = [self.dataArray objectAtIndexSafe:indexPath.section];
    
    if ([object isKindOfClass:[NSArray class]]) {
        WorkAreaModel *obj = [((NSArray *)object) objectAtIndexSafe:indexPath.row];
        if ([obj isKindOfClass:[WorkAreaModel class]]) {
            //工区信息
            WorkTableViewCell *cell = [WorkTableViewCell cellWithTableView:tableView class:[WorkTableViewCell class]];
            cell.model = obj;
            cell.indexPath = indexPath;
            BMWeakSelf
            [cell setBlockClickFav:^(WorkAreaModel *obj, UIButton *btn) {
                if (obj.is_fav) {
                    [weakSelf cancelFavWorkArea:obj button:btn];
                }
                else {
                    [weakSelf addFavWorkArea:obj button:btn];
                }
            }];
            [cell setBlockClickRefresh:^(id obj, NSIndexPath *indexPath) {
                if ([obj isKindOfClass:[WorkAreaModel class]]) {
#warning 刷新数据
                }
            }];
            [cell setBlockClickXiangqing:^(id obj) {
                if ([obj isKindOfClass:[WorkAreaModel class]]) {
                    [weakSelf gotoWorkAreaDetail:obj];
                }
            }];
            
            if (indexPath.row == self.workAreaArray.count-1) {
                [cell showMore:^{
                    [CubeJumpTool goToLineManage];
                }];
            }
            else {
                [cell hideMore];
            }
            
            return cell;
        }
    }
    else if ([object isKindOfClass:[NewsDirModel class]]) {
        NewsModel *obj = [((NewsDirModel *)object).list objectAtIndexSafe:indexPath.row];
        if ([obj isKindOfClass:[NewsModel class]]) {
            //资讯信息
            NewsTableViewCell *cell = [NewsTableViewCell cellWithTableView:tableView class:[NewsTableViewCell class]];
            cell.model = obj;
            
            if (indexPath.row == ((NewsDirModel *)object).list.count-1) {
                cell.isShowFooter = YES;
            }
            
            return cell;
        }
    }

    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    id object = [self.dataArray objectAtIndexSafe:indexPath.section];
    if ([object isKindOfClass:[NSArray class]]) {
        WorkAreaModel *obj = [((NSArray *)object) objectAtIndex:indexPath.row];
        [self gotoWorkAreaDetail:obj];
    }
    else if ([object isKindOfClass:[NewsDirModel class]]) {
        [self.tableView reloadData];
        NewsModel *obj = [((NewsDirModel *)object).list objectAtIndex:indexPath.row];
        [self gotoIndustryNewsDetail:obj];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 220.f;
    }
    else {
        id object = [self.dataArray objectAtIndex:indexPath.section];
        if ([object isKindOfClass:[NewsDirModel class]] && indexPath.row == ((NewsDirModel *)object).list.count-1) {
            return 75.f;
        }
        return 65.f;
    }
}

#pragma mark 跳转
//通知详情
- (void)gotoNoticeDetail:(NoticeModel *)model {
    NoticeDetailViewController *vc = [NoticeDetailViewController new];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

//行业资讯
- (void)gotoMoreIndustryNews:(NewsDirModel *)newsDirModel {
    IndustryNewsViewController *vc = [IndustryNewsViewController new];
    vc.model = newsDirModel;
    [self.navigationController pushViewController:vc animated:YES];
}

//选择工厂
- (void)gotoWorkAreaMore {
    SelectFactoryViewController *selectFactoryVc = [SelectFactoryViewController new];
    selectFactoryVc.style = SelectFactoryControllerStyleScanFactoryDetail;
    [self.navigationController pushViewController:selectFactoryVc animated:YES];
}

//资讯详情
- (void)gotoIndustryNewsDetail:(NewsModel *)model {
    [JumpTool gotoIndustyNewsDetail:model];
}

//工区详情
- (void)gotoWorkAreaDetail:(WorkAreaModel *)model {
    FactoryDetailViewController *vc = [FactoryDetailViewController new];
    vc.areaid = model.areaid;
    vc.navTitle = model.area_name;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
